package com.example.aop.aspect;

import com.example.aop.annotation.Module;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.support.AopUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
public class AuditAspect {
    @Pointcut("execution(public * com.example.aop.controller.*.*(..))")
    public void auditController() {}

    @Around("auditController()")
    public Object afterOperation(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = joinPoint.proceed();

        Module module = getModule(joinPoint);
        if (module != null) {
            System.out.println("有Module注解，记录审计日志");
            System.out.println("模块名："+ module.name() + ", 操作：" + module.operation());
        }
        return result;
    }

    private Module getModule(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = joinPoint.getTarget().getClass().getDeclaredMethod(methodSignature.getName(), methodSignature.getMethod().getParameterTypes());
        return targetMethod.getAnnotation(Module.class);
    }
}
